#!/bin/bash

# Host B - Labgrid Place 配置脚本（最终正确版本）
# 用途：在Host B上配置labgrid place并准备测试环境

set -e  # 遇到错误立即退出

# 配置参数
COORDINATOR="192.168.21.218:20408"
PLACE="clci-board"
RESOURCE_PATTERN="*/resources/ssh_service"

echo "===================================="
echo "Host B - Labgrid Place 配置脚本"
echo "===================================="
echo "Coordinator: $COORDINATOR"
echo "Place: $PLACE"
echo ""

# 1. 检查Coordinator连接
echo "[1/6] 检查Coordinator连接..."
if labgrid-client -x $COORDINATOR resources &>/dev/null; then
    echo "✓ Coordinator连接成功"
else
    echo "✗ 无法连接Coordinator"
    echo "请检查："
    echo "  1. Host A的Coordinator是否运行"
    echo "  2. 防火墙设置"
    echo "  3. 网络连接"
    exit 1
fi
echo ""

# 2. 查看可用资源
echo "[2/6] 查看可用资源..."
labgrid-client -x $COORDINATOR resources
echo ""

# 3. 清理旧Place（如果存在）
echo "[3/6] 清理旧Place..."
if labgrid-client -x $COORDINATOR places 2>/dev/null | grep -q "^$PLACE$"; then
    echo "发现已存在的Place，准备清理..."
    
    # 尝试释放（如果当前用户已获取）
    if labgrid-client -x $COORDINATOR -p $PLACE show 2>/dev/null | grep -q "acquired: $(hostname)/$(whoami)"; then
        echo "释放Place..."
        labgrid-client -x $COORDINATOR -p $PLACE release || echo "释放失败（可能未获取）"
    fi
    
    # 删除Place（注意：delete命令不需要额外参数）
    echo "删除Place..."
    labgrid-client -x $COORDINATOR -p $PLACE delete || echo "删除失败"
else
    echo "无需清理"
fi
echo "✓ 旧Place已清理"
echo ""

# 4. 创建Place（注意：create命令不需要额外参数，place名称由-p指定）
echo "[4/6] 创建Place..."
if labgrid-client -x $COORDINATOR -p $PLACE create; then
    echo "✓ Place创建成功"
else
    echo "✗ Place创建失败"
    exit 1
fi
echo ""

# 5. 添加资源匹配
echo "[5/6] 添加资源匹配..."
echo "匹配模式: $RESOURCE_PATTERN"
if labgrid-client -x $COORDINATOR -p $PLACE add-match $RESOURCE_PATTERN; then
    echo "✓ 资源匹配添加成功"
else
    echo "✗ 资源匹配添加失败"
    exit 1
fi
echo ""

# 6. 获取Place
echo "[6/6] 获取Place..."
if labgrid-client -x $COORDINATOR -p $PLACE acquire; then
    echo "✓ Place获取成功"
else
    echo "✗ Place获取失败"
    exit 1
fi
echo ""

# 验证配置
echo "===================================="
echo "配置完成！验证Place状态："
echo "===================================="
labgrid-client -x $COORDINATOR -p $PLACE show
echo ""

echo "===================================="
echo "✓ 配置成功！"
echo "===================================="
echo "现在可以运行测试脚本："
echo "  python3 test_clci_labgrid.py"
echo "===================================="

